package com.wzh.websocket.service;

import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author zh wang
 * @Create 2025/5/16 16:13
 */
@Service
public class ScheduleService {
    private final SimpMessagingTemplate messagingTemplate;
    private final AtomicInteger counter = new AtomicInteger(0);

    public ScheduleService(SimpMessagingTemplate messagingTemplate) {
        this.messagingTemplate = messagingTemplate;
    }

    // 模拟用户数据存储
    private final Map<String, String> userMessages = Collections.unmodifiableMap(new HashMap<String, String>() {{
        put("user1", "用户1的专属消息");
        put("user2", "用户2的特别通知");
    }});
    @Scheduled(fixedRate = 3000)
    public void checkAndNotify() {
        // 模拟数据库数据
        Map<String, Object> data = new HashMap<>();
        data.put("id", counter.incrementAndGet());
        data.put("time", LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_TIME));

        messagingTemplate.convertAndSend("/topic/time-alerts", data);
        //System.out.println("发送数据：" + data);
    }

    /**
     * 定时推送消息，精准推送
     */
    @Scheduled(fixedRate = 1000)
    public void pushMessages() {
        userMessages.forEach((userId, msg) -> {
            //System.out.println("正在推送消息给用户: " + userId);
            Map<String, Object> payload = new HashMap<>();
            payload.put("time", LocalDateTime.now().format(DateTimeFormatter.ISO_TIME));
            payload.put("content", msg);

            // 定向推送到用户专属队列
            messagingTemplate.convertAndSendToUser(
                    userId,
                    "/queue/messages",
                    payload
            );
        });
        //System.out.println("pushMessages 推送消息：" + DateUtil.getCurrentTime());
    }
}
